package no.spk.util.inforama.service.container.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import no.spk.util.inforama.service.container.ContainerAnalyzer;
import no.spk.util.inforama.service.deployable.Deployable;
import no.spk.util.inforama.service.factory.DeployableFactory;
/**
 * @author Marius
 */
public class ContainerAnalyzerImpl implements ContainerAnalyzer {

	private String containerPath;
	private static final String deployPath = "/deploy/";
	private static final String[] extensions = new String[] { ".war" };
	
	private DeployableFactory deployableFactory;
	
	public ContainerAnalyzerImpl(DeployableFactory deployableFactory, String containerPath) {
		this.deployableFactory = deployableFactory;
		this.containerPath = containerPath;
	}

	public List<Deployable> getDeployables() {
		List<Deployable> deployables = new ArrayList<Deployable>();
		File[] files = getFilesInPath(getAbsoluteDeployPath());
		for (File file : files) {
			if (isDeployable(file.getName()) && file.canRead() && file.isFile()) {
				deployables.add(deployableFactory.createDeployable(file
						.getName(), file.getAbsolutePath(), getExtension(file.getName())));
			}

		}

		return deployables;
	}

	private boolean isDeployable(String fileName) {
		for (String extension : extensions) {
			if (fileName.toLowerCase().endsWith(extension))
				return true;
		}
		return false;
	}
	
	public String getExtension(String filename) {
		
		int indexOfDot = filename.lastIndexOf(".");
		return filename.substring(indexOfDot+1);
	}

	private String getAbsoluteDeployPath() {
		return containerPath + deployPath;
	}

	private File[] getFilesInPath(String path) {
		File root = new File(path);
		if (isDirectory(root) && isAccessible(root) && !isHidden(root)) {
			return root.listFiles();
		}
		throw new RuntimeException("path is not set to a directory: " + path);
	}

	private boolean isHidden(File root) {
		return root.isHidden();
	}

	private boolean isAccessible(File root) {
		return root.canRead();
	}

	private boolean isDirectory(File path) {
		return path != null && path.isDirectory();
	}

}
